/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.concurrent;

import com.google.common.util.concurrent.MoreExecutors;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author ZZH
 * @version 1.0.0 线程池创建类
 */
public class ThreadPoolBuilder {

  /**
   * 创建线程池
   *
   * @param coreSize
   * @param maxSize
   * @param keepAliveTime
   * @param unit
   * @param threadFactory
   * @param queue
   * @param rejectedExecutionHandler
   * @return
   */
  public static ThreadPoolExecutor create(
      int coreSize,
      int maxSize,
      long keepAliveTime,
      TimeUnit unit,
      ThreadFactory threadFactory,
      BlockingQueue<Runnable> queue,
      RejectedExecutionHandler rejectedExecutionHandler) {
    return new ThreadPoolExecutor(
        coreSize, maxSize, keepAliveTime, unit, queue, threadFactory, rejectedExecutionHandler);
  }

  /**
   * 创建调度线程池
   *
   * @param coreSize
   * @param threadFactory
   * @param rejectedExecutionHandler
   * @return
   */
  public static ScheduledThreadPoolExecutor create(
      int coreSize,
      ThreadFactory threadFactory,
      RejectedExecutionHandler rejectedExecutionHandler) {
    return new ScheduledThreadPoolExecutor(coreSize, threadFactory, rejectedExecutionHandler);
  }

  /**
   * @param executor
   * @param terminationTimeout
   * @param timeUnit
   * @return
   */
  public static ExecutorService convertGuavaExecutorService(
      ThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
    return MoreExecutors.getExitingExecutorService(executor, terminationTimeout, timeUnit);
  }

  /**
   * @param executor
   * @param terminationTimeout
   * @param timeUnit
   * @return
   */
  public static ScheduledExecutorService convertGuavaScheduledExecutorService(
      ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
    return MoreExecutors.getExitingScheduledExecutorService(executor, terminationTimeout, timeUnit);
  }
}
